package com.fantasy.demo1.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fantasy.demo1.dto.BookDto;
import com.fantasy.demo1.entity.Book;
import com.fantasy.demo1.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @RequestBody:可以将 HttpRequest body 中的 JSON 类型数据反序列化为合适的 Java 类型
 * ResponseEntity: 表示整个HTTP Response：状态码，标头和正文内容。我们可以使用它来自定义HTTP Response 的内容。
 * 单独使用 @Controller 不加 @ResponseBody的话一般使用在要返回一个视图的情况，这种情况属于比较传统的Spring MVC 的应用，对应于前后端不分离的情况
 * @RestController 返回JSON 或 XML 形式数据
 */

@RestController
@RequestMapping("/api")
@Api
public class BookController {

    @Resource
    BookService bookService;

    private List<Book> books = new ArrayList<>();

    @PostMapping("/book")
    public ResponseEntity<List<Book>> addBook(@RequestBody Book book) {
        books.add(book);
        return ResponseEntity.ok(books);
    }

    /**
     * @PathVariable :取url地址中的参数
     * @param id
     * @return
     */
    @DeleteMapping("/book/{id}")
    public ResponseEntity deleteBookById(@PathVariable("id") int id) {
        books.remove(id);
        return ResponseEntity.ok(books);
    }

    /**
     * @RequestParam  url的查询参数值
     * @param name
     * @return
     */
    @GetMapping("/book")
    public ResponseEntity getBookByName(@RequestParam("name") String name) {
        List<Book> results = books.stream().filter(book -> book.getName().equals(name)).collect(Collectors.toList());
        return ResponseEntity.ok(results);
    }

    @GetMapping("/books")
    public List<Book> getBooks(@RequestParam("name") String name) {
        List<Book> books = bookService.listAllByName(name);
        return books;
    }

    @PostMapping("/book/save")
    public boolean bookSave(@RequestBody Book book) {
        boolean save = bookService.save(book);
        return save;
    }

    @PostMapping("/book/remove")
    public boolean removeBook(@RequestBody String id) {
        boolean bool = bookService.removeById(id);
        return bool;
    }

    @GetMapping("/book/list")
    public List<Book> getAllBook() {
        List<Book> list = bookService.list();
        return list;
    }

    @PostMapping("/book/page")
    public List<Book> bookPage(@RequestBody BookDto bookDto) {
        List<Book> records = bookService.page(bookDto.getPage()).getRecords();
        return records;
    }

    @PostMapping("/book/condition")
    @ApiOperation(value = "条件查询")
    public List<Book> bookCondition(@RequestBody Book book) {
        List<Book> condition = bookService.condition(book);
        System.out.println(condition);
        return condition;
    }


}
